package com.example.excel.controller;

import com.alibaba.fastjson.JSON;
import com.example.excel.data.CommonResponse;
import com.example.excel.data.LongRentCarDto;
import com.example.excel.data.LongRentCarVo;
import com.example.excel.utils.EasyPoiUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author Aaron
 * @since 2021/7/14 11:22
 * <p>描述：</p>
 */
@RestController
@RequestMapping("/longRentCar")
public class LongRentCarController {
    private static final Logger LOGGER = LoggerFactory.getLogger(LongRentCarController.class);

    /**
     * 长租车导入失败数据缓存：parkId_"LongRentCar" <-> List<LongRentCarVo>>
     */
    private static final Map<String, List<LongRentCarVo>> FAILED_DATA_MAP = new HashMap<>();

    @RequestMapping("/excelTemplateDownload")
    public void excelTemplateDownload(HttpServletRequest request, HttpServletResponse response,
                                      @RequestBody LongRentCarVo longRentCarVo) {
        try {
            LOGGER.debug("长租车模板下载：{}", JSON.toJSONString(longRentCarVo));
            EasyPoiUtil.LongRentCar.downloadTemplate(request, response, 1 == longRentCarVo.getIsIE());
        } catch (Exception e) {
            LOGGER.error("长租车模板下载异常：", e);
        }
    }

    @RequestMapping("/excelExport")
    public void excelExport(HttpServletRequest request, HttpServletResponse response,
                            @RequestBody LongRentCarVo longRentCarVo) {
        try {
            LOGGER.debug("长租车导出：{}", JSON.toJSONString(longRentCarVo));

            List<LongRentCarDto> data = new ArrayList<>();
            data.add(LongRentCarDto.builder().parkName("Aaron_2.0测试").sectionName("全场").carOwnerName("张三")
                    .carOwnerTel("13068889889").address("中岳大街").companyName("二大队").carNum("豫RLY123").vehicleType("1")
                    .beginDateStr("2018-09-01").endDateStr("2022-07-30").fee("200").build());
            data.add(LongRentCarDto.builder().parkName("Aaron_3.0坐席").sectionName("外场").carOwnerName("李四")
                    .carOwnerTel("13068889888").address("中岳大街").companyName("二大队").carNum("豫RLY122")
                    .vehicleType("1").beginDateStr("2018-09-01").endDateStr("2022-07-30").fee("200").build());
            data.add(LongRentCarDto.builder().parkName("Aaron_3.0测试").sectionName("内场").carOwnerName("马六")
                    .carOwnerTel("13068889887").address("中岳大街").companyName("二大队").carNum("豫RLY121")
                    .vehicleType("1").beginDateStr("2018-09-01").endDateStr("2022-07-30").fee("200").build());

            EasyPoiUtil.LongRentCar.normalDataExport(request, response, data, longRentCarVo.getIsIE() == 1);
        } catch (Exception e) {
            LOGGER.error("长租车导出异常：", e);
        }
    }

    @RequestMapping("/excelImport")
    public CommonResponse<?> excelImport(@RequestParam("file") MultipartFile file, LongRentCarVo longRentCarVo) {
        try {
            LOGGER.debug("longRentCarImport 入参：{}", JSON.toJSONString(longRentCarVo));
            List<LongRentCarVo> totalImportList = EasyPoiUtil.LongRentCar.excelImport(file);
            if (CollectionUtils.isEmpty(totalImportList) || totalImportList.size() > 1700) {
                LOGGER.error("长租车导入数据量异常：{} 条", CollectionUtils.isEmpty(totalImportList) ? 0 : totalImportList.size());
                return CommonResponse.error("导入记录超过1700条时，导入失败数据无法导出!建议单次导入小于1700条数据");
            }

            List<LongRentCarVo> importFailedList = new ArrayList<>();
            LongRentCarVo errData = totalImportList.get(0);
            errData.setErrField(new StringJoiner("_")
                    .add(errData.getParkName())
                    .add(errData.getCarNum())
                    .add(errData.getVehicleType())
                    .add("莫须有原因").toString());
            importFailedList.add(totalImportList.get(0));
            if (!CollectionUtils.isEmpty(importFailedList)) {
                LOGGER.debug("导入失败数据：{}", JSON.toJSONString(importFailedList));
                FAILED_DATA_MAP.put(longRentCarVo.getParkId() + "_LongRentCar", importFailedList);
                return CommonResponse.success(importFailedList.size(), "导入失败数据：" + importFailedList.size() + "条");
            }

            return CommonResponse.success(0, "导入成功");
        } catch (Exception e) {
            LOGGER.error("导入异常：", e);
            return CommonResponse.error("长租车导入异常");
        }
    }

    @RequestMapping("/failedExcelExport")
    public void failedExcelExport(HttpServletRequest request, HttpServletResponse response, @RequestBody LongRentCarVo longRentCarVo) {
        LOGGER.debug("长租车导入失败数据下载：{}", JSON.toJSONString(longRentCarVo));

        List<LongRentCarVo> longRentCarVoList = FAILED_DATA_MAP.get(longRentCarVo.getParkId() + "_LongRentCar");
        if (CollectionUtils.isEmpty(longRentCarVoList)) {
            LOGGER.error("长租车导入失败数据下载失败：{} 无数据", longRentCarVo.getParkId());
            return;
        }

        try {
            EasyPoiUtil.LongRentCar.failedDataExport(request, response, longRentCarVoList, 1 == longRentCarVo.getIsIE());
        } catch (Exception e) {
            LOGGER.error("长租车导出失败数据异常：{} {}", longRentCarVoList, e);
        }
    }

}
